package org.flowable.pz.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.flowable.pz.exception.FlowableCustomException;
import org.flowable.pz.expand.FlowableUserExpand;
import org.flowable.engine.IdentityService;
import org.springframework.stereotype.Component;

/**
 * 对有 @FlowableAuth 注解的方法，进行认证用户设置操作
 * */
@Aspect
@Component
@Slf4j
public class FlowableAuthAspect {

    private final FlowableUserExpand flowableUserExpand;
    private final IdentityService identityService;

    public FlowableAuthAspect(FlowableUserExpand flowableUserExpand,
                              IdentityService identityService){
        this.flowableUserExpand = flowableUserExpand;
        this.identityService = identityService;
    }

    @Pointcut("@annotation(org.flowable.pz.anno.FlowableAuth)")
    private void point(){}

    @Around("point()")
    public Object authOperator(ProceedingJoinPoint pjp) throws Throwable{
        log.info("AOP 认证！！！！");
        String currentUserId = flowableUserExpand.getCurrentUserId();
        if(currentUserId == null || currentUserId.isEmpty()){
            throw new FlowableCustomException("当前认证用户为空！！！");
        }
        identityService.setAuthenticatedUserId( flowableUserExpand.getCurrentUserId() );
        try{
            return pjp.proceed();
        } finally {
            //取消注释
            identityService.setAuthenticatedUserId(null);
        }
    }

}
